package org.janon.httpproxy.server.method;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import org.janon.httpproxy.ClientReadFromServer;
import org.janon.httpproxy.HttpModel;
import org.janon.httpproxy.HttpSession;
import org.janon.httpproxy.HttpUtil;
import org.janon.httpproxy.RequestLogStream;

public class ConnectContinueMethod
{
	public static ClientReadFromServer doMethod(HttpModel httpModel, BufferedInputStream server_in, BufferedOutputStream server_out, BufferedInputStream client_in, BufferedOutputStream client_out, HttpSession session, RequestLogStream rls) throws Exception
	{
		String key = httpModel.getUrl().getUrl();
		
//		client_out.write((httpModel.getHttpType() + " 304 Not Modified" + HttpUtil.CRLF).getBytes());
		client_out.write((httpModel.getHttpType() + " 200 OK" + HttpUtil.CRLF).getBytes());
		HttpUtil.sendInitHeader(client_out);
		client_out.write(("Set-Cookies: " + key + HttpUtil.CRLF).getBytes());
		client_out.write(HttpUtil.CRLF.getBytes());
		client_out.flush();
		
		ConnectMap.getInstance().setClientOutputStream(key, client_out);
		String flag = ConnectMap.getInstance().getFlag(key);
		if(httpModel.getContinueConnectionActID()!=null && httpModel.getContinueConnectionActID().equals("REFRESH"))
		{
			//TODO DO NOTHING
		}
		else if(httpModel.isHasContent())
		{
			try
			{
				ConnectMap.getInstance().write(key, httpModel.getContent(), 0, httpModel.getContentLength());
			} catch (Exception e)
			{
				ConnectMap.getInstance().close(key);
			}
		}
		else
		{
			ConnectMap.getInstance().close(key);
		}
		
		if(ConnectMap.getInstance().isClose(key))
		{
			ConnectMap.getInstance().remove(key);
		}
		else
		{
			int in = 0;
			while(ConnectMap.getInstance().getFlag(key).equals(flag))
			{
				Thread.sleep(5000);
				in++;
				if(in==60)
				{
					ConnectMap.getInstance().remove(key);
					break;
				}
			}
		}
		return null;
	}
}
